<template>
  <el-dialog v-model="addOrEditUerVisible" :title="userId === 0 ? '创建用户' : '编辑用户'" width="600">
    <el-form ref="formRef" style="max-width: 600px" :model="formCustom" status-icon :rules="rules" label-width="auto">
      <el-form-item label="组织机构" prop="org_id">
        <el-tree-select
          v-model="formCustom.org_id"
          style="width: 100%"
          :props="props"
          :data="treeData"
          placeholder="请选择"
          check-strictly
        />
      </el-form-item>
      <el-form-item label="用户账号" prop="username">
        <el-input v-model="formCustom.username" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户姓名" prop="name">
        <el-input v-model="formCustom.name" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户工号" prop="uniq_code">
        <el-input v-model="formCustom.uniq_code" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="用户类型" prop="type">
        <el-select ref="type" v-model="formCustom.type" filterable placeholder="请选择" clearable>
          <el-option v-for="item of typeList" :value="item.key" :key="item.key" :label="item.verbose">{{
            item.verbose
          }}</el-option>
        </el-select>
        <div v-if="formCustom.type === 'ADMIN'" style="color: red" class="ant-form-explain">
          管理员用户拥有系统的全部权限，请谨慎选择。
        </div>
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile_phone">
        <el-input v-model="formCustom.mobile_phone" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="办公电话" prop="office_phone">
        <el-input v-model="formCustom.office_phone" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="电子邮箱" prop="email">
        <el-input v-model="formCustom.email" type="text" autocomplete="off" />
      </el-form-item>
      <el-form-item label="关联角色" prop="role">
        <el-select
          ref="role"
          v-model="formCustom.role"
          show-search
          mode="multiple"
          placeholder="请选择"
          filterable
          clearable
          multiple
          collapse-tags
          :max-collapse-tags="3"
        >
          <el-option v-for="item of roleList" :value="item.id" :key="item.id" :label="item.name" :disabled="item.id === 1">
            {{ item.name }}
          </el-option>
        </el-select>
        <div style="color: red" class="ant-form-explain" v-if="false">您暂无关联角色的权限，无法编辑角色</div>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addOrEditUerVisible = false">取消</el-button>
        <el-button type="primary" @click="submit(formRef)" :loading="loading">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="AddOrEditRole">
import { ref, reactive } from "vue";
import { getRoleList } from "@/api/modules/roleManagement";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { getTreeList, getUserDetail, userCreate, userModify } from "@/api/modules/userManagement";
const formRef = ref<FormInstance>();
const typeList = [
  { key: "ADMIN", verbose: "管理员" },
  { key: "USER", verbose: "普通用户" }
];
// 用户id
let userId: any = 0;
const addOrEditUerVisible = ref<boolean>(false);
const treeData = ref<any>([]);
const props = {
  label: "name",
  value: "id",
  children: "children"
};
const defaultRole = [1];
let formCustom = ref<any>({
  username: "",
  uniq_code: "",
  name: "",
  mobile_phone: "",
  email: "",
  office_phone: "",
  type: "USER",
  role: "",
  org_id: null
});
const rules = reactive<FormRules<typeof formCustom>>({
  uniq_code: [{ min: 0, max: 64, message: "长度需为0~64个字符", trigger: ["blur", "change"] }],
  username: [
    { required: true, message: "内容不能为空", trigger: ["blur", "change"] },
    {
      message: "以英文字母开头，只能包含英文字母、数字、下划线(5~20个字符)",
      trigger: ["blur", "change"],
      pattern: /^[a-zA-Z][a-zA-Z0-9_]{4,19}$/
    }
  ],
  name: [{ min: 0, max: 64, message: "长度需为0~64个字符", trigger: ["blur", "change"] }],
  mobile_phone: [
    {
      required: false,
      message: "请输入正确的手机格式（以1开头的11位数字）",
      trigger: ["blur", "change"],
      pattern: /^1\d{10}$/
    }
  ],
  email: [
    // { required: true, message: '内容不能为空', trigger: ['blur', 'change'] },
    {
      required: false,
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
      pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
    },
    { min: 0, max: 64, message: "长度需为0~64个字符", trigger: ["blur", "change"] }
  ],
  office_phone: [
    {
      required: false,
      message: "请输入正确的办公电话（以0开头的区号+固话号码）",
      trigger: ["blur", "change"],
      pattern: /(^1[356789]\d{9}$)|(^\(?0\d{2}[)-]?\d{8}$)|(^\(?0\d{3}[)-]?\d{7}$)/
    }
  ],
  type: [{ required: true, message: "内容不能为空", trigger: "change" }],
  org_id: [{ required: true, message: "内容不能为空", trigger: "change" }]
});
// 获取用户详情
const getDetail = async () => {
  const { data } = await getUserDetail(userId);
  formCustom.value = {
    username: data.username,
    uniq_code: data.uniq_code,
    name: data.name,
    mobile_phone: data.mobile_phone,
    email: data.email,
    office_phone: data.office_phone,
    type: data.type.key,
    role: data.role,
    org_id: data.org ? data.org.id : null
  };
};
// 获取角色列表
let roleList = ref<any>([]);
const getRoleCollect = async () => {
  const { data } = await getRoleList();
  roleList.value = data;
};
// 获取组织树
const getTreeFilter = async () => {
  const { data } = await getTreeList();
  treeData.value = [data];
};

let loading = false;
const openDialog = (id: number = 0) => {
  userId = id;
  loading = false;
  addOrEditUerVisible.value = true;
  getRoleCollect();
  getTreeFilter();
  if (userId !== 0) {
    getDetail();
  } else {
    formRef.value?.resetFields();
    formCustom.value["role"] = defaultRole;
  }
};
const closeDialog = () => {
  loading = false;
  addOrEditUerVisible.value = false;
};
// emit
const emit = defineEmits<{
  refresh: [];
}>();

const submit = async (formEl: FormInstance | undefined) => {
  loading = true;
  const paramsObj = { ...formCustom.value };
  // 加上默认角色
  const otherRole = paramsObj["role"].filter(a => !defaultRole.includes(a));
  paramsObj["role"] = defaultRole.concat(otherRole);
  if (userId === 0) {
    // 创建
    const { data } = await userCreate(paramsObj);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addOrEditUerVisible.value = false;
      // 重置表单
      formCustom.value = {
        username: "",
        uniq_code: "",
        name: "",
        mobile_phone: "",
        email: "",
        office_phone: "",
        type: "USER",
        role: "",
        org_id: null
      };
      emit("refresh");
    }
  } else {
    // 编辑
    const { data } = await userModify(userId, paramsObj);
    if (data) {
      ElMessage({
        type: "success",
        message: `操作成功!`
      });
      addOrEditUerVisible.value = false;
      // 重置表单
      formEl?.resetFields();
      emit("refresh");
    }
  }
};
defineExpose({
  openDialog,
  closeDialog
});
</script>
<style lang="scss" scoped>
.filter {
  width: 100%;
  height: 500px;
  overflow-y: auto;
  border: none;
  box-shadow: none;
}
</style>
